import 'package:flutter/material.dart';
import '../models/order.dart';
import '../widgets/empty_state.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../pages/order_detail_page.dart';  // 添加导入

/// 订单页面
class OrdersPage extends StatefulWidget {
  const OrdersPage({super.key});

  @override
  State<OrdersPage> createState() => _OrdersPageState();
}

class _OrdersPageState extends State<OrdersPage> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  
  // 更新刷新控制器的 key
  final Map<String, RefreshController> _refreshControllers = {
    '全部': RefreshController(),
    '待服务': RefreshController(),
    '服务中': RefreshController(),
    '已完成': RefreshController(),
    '已取消': RefreshController(),
  };

  // 更新订单数据的 key
  final Map<String, List<Order>> _orderData = {
    '全部': [
      Order(
        id: '001',
        fromAddress: '北京市东城区东长安街1号',
        address: '北京市朝阳区建国路88号',
        status: '服务中',
        time: '2024-03-20 14:30',
        price: 288.00,
        customerName: '张先生',
        customerPhone: '138****8888',
        serviceType: '居民搬家',
        requirements: ['有电梯', '需要拆装家具', '需要包装服务'],
        distance: 3.5,
      ),
      // ... 其他订单
    ],
    '待服务': [
      Order(
        id: '002',
        fromAddress: '北京市海淀区学院路15号',
        address: '北京市海淀区中关村大街1号',
        status: '待服务',
        time: '2024-03-20 15:00',
        price: 366.00,
        customerName: '李女士',
        customerPhone: '139****9999',
        serviceType: '办公室搬迁',
        requirements: ['需要搬运大型设备', '周末搬迁'],
        distance: 2.8,
      ),
    ],
    '服务中': [
      Order(
        id: '001',
        fromAddress: '北京市东城区东长安街1号',
        address: '北京市朝阳区建国路88号',
        status: '服务中',
        time: '2024-03-20 14:30',
        price: 288.00,
        customerName: '张先生',
        customerPhone: '138****8888',
        serviceType: '居民搬家',
        requirements: ['有电梯', '需要拆装家具', '需要包装服务'],
        distance: 3.5,
      ),
    ],
    '已完成': [
      Order(
        id: '003',
        fromAddress: '北京市西城区复兴门外大街1号',
        address: '北京市西城区西长安街1号',
        status: '已完成',
        time: '2024-03-19 13:20',
        price: 199.00,
        customerName: '王先生',
        customerPhone: '137****7777',
        serviceType: '居民搬家',
        requirements: ['有电梯', '需要包装服务'],
        distance: 1.5,
      ),
    ],
    '已取消': [], // 空列表用于测试缺省页
  };

  // 订单状态列表
  final List<String> _orderStatuses = [
    '全部',
    '待服务',
    '服务中',
    '已完成',
    '已取消',
  ];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _orderStatuses.length, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    // 释放刷新控制器
    _refreshControllers.values.forEach((controller) => controller.dispose());
    super.dispose();
  }

  /// 构建操作按钮
  Widget _buildActionButton(
    String text,
    Color color,
    VoidCallback onPressed, {
    Color? textColor,
  }) {
    return SizedBox(
      height: 32,
      child: ElevatedButton(
        onPressed: onPressed,
        style: ElevatedButton.styleFrom(
          backgroundColor: color,
          foregroundColor: textColor ?? Colors.white,
          elevation: 0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(6),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 12),
        ),
        child: Text(
          text,
          style: const TextStyle(
            fontSize: 13,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }

  /// 构建地址行
  Widget _buildAddressRow(String label, String? address, IconData icon) {
    return Row(
      children: [
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
          decoration: BoxDecoration(
            color: Colors.grey[300],
            borderRadius: BorderRadius.circular(4),
          ),
          child: Text(
            label,
            style: const TextStyle(fontSize: 12),
          ),
        ),
        const SizedBox(width: 8),
        Expanded(
          child: Text(
            address ?? '地址未填写',
            style: const TextStyle(fontSize: 14),
          ),
        ),
      ],
    );
  }

  /// 构建服务类型和要求标签
  Widget _buildTags(String? serviceType, List<String>? requirements) {
    return Wrap(
      spacing: 8,
      runSpacing: 8,
      children: [
        if (serviceType != null)
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
            decoration: BoxDecoration(
              color: Theme.of(context).primaryColor.withOpacity(0.1),
              borderRadius: BorderRadius.circular(4),
            ),
            child: Text(
              serviceType,
              style: TextStyle(
                color: Theme.of(context).primaryColor,
                fontSize: 12,
              ),
            ),
          ),
        if (requirements != null)
          ...requirements.map((req) => Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
            decoration: BoxDecoration(
              color: Colors.grey[100],
              borderRadius: BorderRadius.circular(4),
            ),
            child: Text(
              req,
              style: TextStyle(
                color: Colors.grey[700],
                fontSize: 12,
              ),
            ),
          )),
      ],
    );
  }

  /// 构建订单列表项
  Widget _buildOrderItem(Order order) {
    final fromAddress = order.fromAddress;
    final toAddress = order.address;
    final customerName = order.customerName;
    final customerPhone = order.customerPhone;
    final serviceType = order.serviceType;
    final requirements = order.requirements;

    return Card(
      margin: const EdgeInsets.fromLTRB(12, 8, 12, 8),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
      elevation: 0,
      color: Colors.white,
      child: InkWell(
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => OrderDetailPage(order: order),
            ),
          );
        },
        borderRadius: BorderRadius.circular(8),
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            border: Border.all(color: const Color(0xFFEEEEEE)),
          ),
          child: Padding(
            padding: const EdgeInsets.all(12),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 订单头部信息 - 交换状态和时间的位置
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 状态标签
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 8,
                        vertical: 3,
                      ),
                      decoration: BoxDecoration(
                        color: _getStatusColor(order.status).withOpacity(0.1),
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: Text(
                        order.status,
                        style: TextStyle(
                          color: _getStatusColor(order.status),
                          fontSize: 12,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                    // 时间显示
                    Text(
                      order.time,
                      style: TextStyle(
                        color: Colors.grey[600],
                        fontSize: 13,
                      ),
                    ),
                  ],
                ),

                const Padding(
                  padding: EdgeInsets.symmetric(vertical: 8),
                  child: Divider(
                    height: 1,
                    color: Color(0xFFF0F0F0),
                  ),
                ),

                // 地址信息
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                  decoration: BoxDecoration(
                    color: const Color(0xFFFAFAFA),
                    borderRadius: BorderRadius.circular(4),
                    border: Border.all(color: const Color(0xFFEEEEEE)),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '搬出',
                            style: TextStyle(
                              fontSize: 13,
                              color: Colors.grey[700],
                            ),
                          ),
                          const SizedBox(width: 16),
                          Expanded(
                            child: Text(
                              fromAddress ?? '地址未填写',
                              style: const TextStyle(fontSize: 14),
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 8),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '搬入',
                            style: TextStyle(
                              fontSize: 13,
                              color: Colors.grey[700],
                            ),
                          ),
                          const SizedBox(width: 16),
                          Expanded(
                            child: Text(
                              toAddress,
                              style: const TextStyle(fontSize: 14),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),

                const SizedBox(height: 12),

                // 客户信息和价格并排显示
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    if (customerName != null || customerPhone != null)
                      Row(
                        children: [
                          const Icon(Icons.person_outline, size: 16, color: Colors.grey),
                          const SizedBox(width: 4),
                          if (customerName != null)
                            Text(
                              customerName,
                              style: const TextStyle(fontSize: 13),
                            ),
                          if (customerPhone != null) ...[
                            const SizedBox(width: 8),
                            Text(
                              customerPhone,
                              style: const TextStyle(fontSize: 13),
                            ),
                          ],
                        ],
                      )
                    else
                      const SizedBox.shrink(),
                    
                    // 价格显示
                    Text(
                      '¥${order.price.toStringAsFixed(2)}',
                      style: const TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: Color(0xFF333333),
                      ),
                    ),
                  ],
                ),

                if (serviceType != null || (requirements != null && requirements.isNotEmpty)) ...[
                  const SizedBox(height: 8),
                  _buildTags(serviceType, requirements),
                ],

                const SizedBox(height: 12),
                const Divider(
                  height: 1,
                  color: Color(0xFFEEEEEE),
                ),
                Container(
                  decoration: const BoxDecoration(
                    border: Border(
                      top: BorderSide(
                        color: Color(0xFFEEEEEE),
                        width: 1,
                      ),
                    ),
                  ),
                  padding: const EdgeInsets.only(top: 12),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      _buildActionButton(
                        '联系客户',
                        const Color(0xFFF5F5F5),
                        () => _contactCustomer(order),
                        textColor: Colors.black87,
                      ),
                      const SizedBox(width: 12),
                      _buildActionButton(
                        _getMainActionText(order.status),
                        const Color(0xFFFF5722),
                        () => _handleMainAction(order),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 获取状态对应的颜色
  Color _getStatusColor(String status) {
    switch (status) {
      case '进行中':
        return Colors.blue;
      case '已完成':
        return Colors.green;
      case '已取消':
        return Colors.grey;
      case '待接单':
        return const Color(0xFFFF5722);
      default:
        return Colors.grey;
    }
  }

  // 获取主操作按钮文本
  String _getMainActionText(String status) {
    switch (status) {
      case '进行中':
        return '完成订单';
      case '待接单':
        return '立即接单';
      default:
        return '查看详情';
    }
  }

  /// 处理订单状态更新
  Future<void> _updateOrderStatus(Order order, String newStatus) async {
    try {
      // 显示加载对话框
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => const Center(
          child: CircularProgressIndicator(),
        ),
      );

      // 模拟网络请求
      await Future.delayed(const Duration(seconds: 1));

      if (!mounted) return;
      Navigator.pop(context); // 关闭加载对话框

      setState(() {
        final index = _orderData[_getCurrentTab()]!.indexWhere((o) => o.id == order.id);
        if (index != -1) {
          _orderData[_getCurrentTab()]![index] = Order(
            id: order.id,
            fromAddress: order.fromAddress,
            address: order.address,
            status: newStatus,
            time: order.time,
            price: order.price,
            customerName: order.customerName,
            customerPhone: order.customerPhone,
            serviceType: order.serviceType,
            requirements: order.requirements,
            distance: order.distance,
          );
        }
      });

      // 显示成功提示
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('订单${newStatus}成功'),
            behavior: SnackBarBehavior.floating,
          ),
        );
      }
    } catch (e) {
      if (!mounted) return;
      Navigator.pop(context); // 关闭加载对话框
      
      // 显示错误提示
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('操作失败：${e.toString()}'),
          behavior: SnackBarBehavior.floating,
        ),
      );
    }
  }

  /// 获取当前标签页
  String _getCurrentTab() {
    switch (_tabController.index) {
      case 0:
        return '全部';
      case 1:
        return '待服务';
      case 2:
        return '服务中';
      case 3:
        return '已完成';
      case 4:
        return '已取消';
      default:
        return '全部';
    }
  }

  /// 处理取消订单
  Future<void> _cancelOrder(Order order) async {
    final result = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认取消订单'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('取消原因'),
            const SizedBox(height: 12),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 12),
              decoration: BoxDecoration(
                color: const Color(0xFFF5F5F5),
                borderRadius: BorderRadius.circular(8),
                border: Border.all(
                  color: const Color(0xFFEEEEEE),
                ),
              ),
              child: DropdownButtonHideUnderline(
                child: DropdownButton<String>(
                  isExpanded: true,
                  value: '临时有事',
                  items: [
                    '临时有事',
                    '价格不合适',
                    '距离太远',
                    '其他原因',
                  ].map((String value) {
                    return DropdownMenuItem<String>(
                      value: value,
                      child: Text(value),
                    );
                  }).toList(),
                  onChanged: (value) {
                    // TODO: 处理选择
                  },
                ),
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('再想想'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            style: TextButton.styleFrom(
              foregroundColor: Colors.red,
            ),
            child: const Text('确认取消'),
          ),
        ],
      ),
    );

    if (result == true) {
      await _updateOrderStatus(order, '已取消');
    }
  }

  /// 处理完成订单
  Future<void> _completeOrder(Order order) async {
    final result = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认完成订单'),
        content: const Text('确认已完成搬家服务？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            style: TextButton.styleFrom(
              foregroundColor: const Color(0xFFFF5722),
            ),
            child: const Text('确认'),
          ),
        ],
      ),
    );

    if (result == true) {
      await _updateOrderStatus(order, '已完成');
    }
  }

  /// 联系客户
  Future<void> _contactCustomer(Order order) async {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('联系客户'),
        content: Text('是否拨打 ${order.customerPhone}？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              // 使用系统自带的方式打开拨号盘
              final Uri telUri = Uri(
                scheme: 'tel',
                path: order.customerPhone,
              );
              try {
                Navigator.pushNamed(context, telUri.toString());
              } catch (e) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(
                    content: Text('无法拨打电话'),
                    behavior: SnackBarBehavior.floating,
                  ),
                );
              }
            },
            child: const Text(
              '拨打',
              style: TextStyle(
                color: Color(0xFFFF5722),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 处理主要操作
  void _handleMainAction(Order order) {
    switch (order.status) {
      case '进行中':
        _completeOrder(order);
        break;
      case '待接单':
        // TODO: 实现接单逻辑
        break;
      default:
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => OrderDetailPage(order: order),
          ),
        );
    }
  }

  // 模拟下拉刷新
  Future<void> _onRefresh(String type) async {
    // 模拟网络请求延迟
    await Future.delayed(const Duration(seconds: 2));
    // TODO: 实际开发中这里应该调用API获取最新数据
    setState(() {
      // 模拟刷新数据
      if (type == '全部') {
        _orderData[type]?.insert(0, Order(
          id: DateTime.now().toString(),
          address: '北京市朝阳区新增测试地址',
          fromAddress: '北京市海淀区新增起始地址',
          status: '待接单',
          time: DateTime.now().toString().substring(0, 16),
          price: 299.00,
          customerName: '新客户',
          customerPhone: '135****1234',
          serviceType: '居民搬家',
          requirements: ['新订单测试'],
        ));
      }
    });
    _refreshControllers[type]?.refreshCompleted();
  }

  // 模拟上拉加载
  Future<void> _onLoading(String type) async {
    await Future.delayed(const Duration(seconds: 1));
    // TODO: 实际开发中这里应该调用API获取更多数据
    setState(() {
      // 模拟加载更多数据
      if (_orderData[type]!.length < 20) { // 限制模拟数据数量
        _orderData[type]?.add(Order(
          id: DateTime.now().toString(),
          address: '北京市西城区加载更多测试地址',
          fromAddress: '北京市东城区加载更多起始地址',
          status: type == '全部' ? '待接单' : (type == '已完成' ? '已完成' : '已取消'),
          time: DateTime.now().toString().substring(0, 16),
          price: 199.00,
          customerName: '加载更多测试',
          customerPhone: '136****5678',
          serviceType: '居民搬家',
          requirements: ['加载更多测试'],
        ));
        _refreshControllers[type]?.loadComplete();
      } else {
        _refreshControllers[type]?.loadNoData();
      }
    });
  }

  /// 构建订单列表
  Widget _buildOrderList(List<Order> orders, String type) {
    if (orders.isEmpty) {
      String message;
      String? subMessage;
      IconData icon;

      switch (type) {
        case '全部':
          message = '暂无进行中的订单';
          subMessage = '接单后的订单会显示在这里';
          icon = Icons.local_shipping_outlined;
          break;
        case '待服务':
          message = '暂无进行中的订单';
          subMessage = '接单后的订单会显示在这里';
          icon = Icons.local_shipping_outlined;
          break;
        case '服务中':
          message = '暂无进行中的订单';
          subMessage = '接单后的订单会显示在这里';
          icon = Icons.local_shipping_outlined;
          break;
        case '已完成':
          message = '暂无已完成订单';
          subMessage = '完成的订单会显示在这里';
          icon = Icons.task_outlined;
          break;
        case '已取消':
          message = '暂无已取消订单';
          icon = Icons.cancel_outlined;
          break;
        default:
          message = '暂无订单';
          icon = Icons.inbox_outlined;
      }

      return EmptyState(
        message: message,
        subMessage: subMessage,
        icon: icon,
        onRefresh: () => _onRefresh(type),
      );
    }
    
    return SmartRefresher(
      controller: _refreshControllers[type]!,
      enablePullDown: true,
      enablePullUp: true,
      header: CustomHeader(
        builder: (BuildContext context, RefreshStatus? mode) {
          Widget body;
          if (mode == RefreshStatus.idle) {
            body = const Text("下拉刷新");
          } else if (mode == RefreshStatus.refreshing) {
            body = Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                SizedBox(
                  width: 16,
                  height: 16,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFFF5722)),
                  ),
                ),
                const SizedBox(width: 8),
                const Text("加载中..."),
              ],
            );
          } else if (mode == RefreshStatus.canRefresh) {
            body = const Text("松开刷新");
          } else if (mode == RefreshStatus.completed) {
            body = const Text("刷新成功");
          } else {
            body = const Text("刷新失败");
          }
          return Container(
            height: 44,
            alignment: Alignment.center,
            child: DefaultTextStyle(
              style: TextStyle(
                color: Colors.grey[600],
                fontSize: 13,
              ),
              child: body,
            ),
          );
        },
      ),
      footer: CustomFooter(
        builder: (BuildContext context, LoadStatus? mode) {
          Widget body;
          if (mode == LoadStatus.idle) {
            body = const Text("上拉加载更多");
          } else if (mode == LoadStatus.loading) {
            body = Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                SizedBox(
                  width: 16,
                  height: 16,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFFF5722)),
                  ),
                ),
                const SizedBox(width: 8),
                const Text("加载中..."),
              ],
            );
          } else if (mode == LoadStatus.failed) {
            body = const Text("加载失败，点击重试");
          } else if (mode == LoadStatus.canLoading) {
            body = const Text("松开加载更多");
          } else {
            body = const Text("没有更多数据了");
          }
          return SizedBox(
            height: 44,
            child: Center(
              child: DefaultTextStyle(
                style: TextStyle(
                  fontSize: 13,
                  color: Colors.grey[600],
                ),
                child: body,
              ),
            ),
          );
        },
      ),
      onRefresh: () => _onRefresh(type),
      onLoading: () => _onLoading(type),
      child: ListView.builder(
        itemCount: orders.length,
        itemBuilder: (context, index) => _buildOrderItem(orders[index]),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F5),
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        toolbarHeight: 56,
        flexibleSpace: SafeArea(
          child: Column(
            children: [
              const SizedBox(height: 8),
              TabBar(
                controller: _tabController,
                isScrollable: false,
                labelColor: const Color(0xFFFF5722),
                unselectedLabelColor: Colors.grey[700],
                labelStyle: const TextStyle(
                  fontSize: 13,
                  fontWeight: FontWeight.w500,
                ),
                unselectedLabelStyle: const TextStyle(
                  fontSize: 13,
                  fontWeight: FontWeight.normal,
                ),
                indicatorColor: const Color(0xFFFF5722),
                indicatorSize: TabBarIndicatorSize.label,
                padding: EdgeInsets.zero,
                dividerColor: Colors.transparent,
                labelPadding: const EdgeInsets.symmetric(horizontal: 4),
                tabs: _orderStatuses.map((status) => Tab(
                  child: Text(
                    status,
                    style: const TextStyle(height: 1),
                  ),
                )).toList(),
              ),
            ],
          ),
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: _orderStatuses.map((status) {
          return _buildOrderList(_orderData[status]!, status);
        }).toList(),
      ),
    );
  }
} 